import { Teleport, defineComponent, onMounted } from "vue";
import LToast from "./LToast";

// const defaultDuration = 3000;
const defaultDuration = 3000;

export default defineComponent({
  name: "LNotice",
  props: [
    "content",
    "type",
    "noticeKey",
    "onClose",
  ],
  setup(props) {
    let closeTimer = null;

    const duration = defaultDuration;
    const startCloseTimer = () => {
      if (duration) {
        closeTimer = setTimeout(() =>{
          close();
        }, duration);
      }
    };

    const clearClosTimer = () => {
      if (closeTimer) {
        clearTimeout(closeTimer);
        closeTimer = null;
      } 
    };

    const close = () => {
      clearClosTimer();
      const { onClose, noticeKey } = props;
      if (onClose) {
        onClose(noticeKey);
      }
    };

    onMounted(() => {
      startCloseTimer();
    });

    return () => {
      const { holder } = props;
      if (holder) {
        return (
          <Teleport to={holder}>
            <LToast content={props.content} type={props.type} index={props.index} />
          </Teleport>
        );
      }
      return <LToast content={props.content} type={props.type} index={props.index} />;
    };
  },
});